package file.server

import groovy.json.JsonOutput
import java.text.SimpleDateFormat

class AttachmentController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    AttachmentService attachmentService

    def upload()
    {
        log.info "******************** upload inParams ************************"

        def file = request.getFile("file")
        def fileType = request.getParameter("fileType")

        def externalId = UUID.randomUUID().toString()
        def webroot = servletContext.getRealPath("/")

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy")
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM")
        SimpleDateFormat sdf3 = new SimpleDateFormat("dd")
        Date date = new Date()

        File folder = attachmentService.createFolder(webroot, sdf1.format(date), sdf2.format(date), sdf3.format(date))
        File fileImage = new File(folder, "${externalId}.${fileType}")
        file.transferTo(fileImage)

        log.info "******************** upload outParams ***********************"
        log.info "externalId: " + externalId + "\n"

        def resultMap = [externalId: externalId]
        render JsonOutput.toJson(resultMap), status: 200
    }
}